/**
 * 图案管理模块
 */
const {
	patternCollection,
	dbCmd
} = require('../../common/constants')
const {
	ERROR
} = require('../../common/error')
const {
	transformMultiLangData
} = require('../../lib/transform')

module.exports = {
	/**
	 * 获取图案列表
	 * @param {object} params 查询参数
	 * @returns {object} 图案列表
	 */
	async getPatternList(params = {}) {
		const {
			category,
			page = 1,
			limit = 20,
			keyword,
			sortBy = 'create_time'
		} = params

		try {
			
			let whereCondition = {
				status: 1  // 只获取已发布的图案
			}
			
			// 分类筛选
			if (category && category !== 'all') {
				whereCondition.category = category
			}
			
			// 关键词搜索 - 支持多语言搜索（仅搜索图案名称）
			if (keyword) {
				whereCondition = dbCmd.and([
					whereCondition,
					dbCmd.or([
						{ 'pattern_name.zh-Hans': new RegExp(keyword, 'i') },
						{ 'pattern_name.en': new RegExp(keyword, 'i') },
						{ 'pattern_name.ja': new RegExp(keyword, 'i') },
						{ 'pattern_name.ko': new RegExp(keyword, 'i') },
						{ 'pattern_name.es': new RegExp(keyword, 'i') },
						{ 'pattern_name.fr': new RegExp(keyword, 'i') }
					])
				])
			}
			
			// 排序条件
			let orderBy = 'create_time'
			let orderType = 'desc'
			
			switch (sortBy) {
				case 'popular':
					orderBy = 'download_count'
					break
				case 'newest':
					orderBy = 'create_time'
					break
				case 'favorite':
					orderBy = 'favorite_count'
					break
				case 'name':
					orderBy = 'pattern_name.zh-Hans' // 默认按中文名排序
					orderType = 'asc'
					break
			}
			
			// 分页查询
			const skip = (page - 1) * limit
			const patternResult = await patternCollection
				.where(whereCondition)
				.orderBy(orderBy, orderType)
				.skip(skip)
				.limit(limit)
				.get()
			
			// 获取总数
			const countResult = await patternCollection
				.where(whereCondition)
				.count()

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 使用通用转换方法转换数据格式
			const transformedData = transformMultiLangData(patternResult.data, language, {
				multiLangFields: ['pattern_name', 'description'],
				keepFields: ['category', 'difficulty', 'tags', 'pattern_file', 'cover_image', 'preview_image', 'thumbnail', 'duration', 'play_time', 'download_count', 'favorite_count', 'status', 'is_featured', 'designer', 'is_premium', 'compatible_devices', 'supported_languages', 'create_time', 'update_time'],
				idMapping: { '_id': 'id' }
			})

			return {
				errCode: 0,
				data: {
					list: transformedData,
					total: countResult.total,
					page,
					limit,
					totalPages: Math.ceil(countResult.total / limit)
				}
			}
		} catch (error) {
			console.error('获取图案列表失败:', error)
			throw {
				errCode: ERROR.DICT_GET_FAILED
			}
		}
	},

	/**
	 * 获取图案详情
	 * @param {string} patternId 图案ID
	 * @returns {object} 图案详情
	 */
	async getPatternDetail(patternId) {
		if (!patternId) {
			throw {
				errCode: ERROR.PARAM_ERROR
			}
		}

		try {			
			const patternResult = await patternCollection.doc(patternId).get()
			
			if (patternResult.data.length === 0) {
				throw {
					errCode: ERROR.DATA_NOT_FOUND
				}
			}

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 使用通用转换方法转换数据格式
			const transformedData = transformMultiLangData(patternResult.data[0], language, {
				multiLangFields: ['pattern_name', 'description'],
				keepFields: ['category', 'difficulty', 'tags', 'pattern_file', 'cover_image', 'preview_image', 'thumbnail', 'duration', 'play_time', 'download_count', 'favorite_count', 'status', 'is_featured', 'designer', 'is_premium', 'compatible_devices', 'supported_languages', 'create_time', 'update_time', 'create_uid'],
				idMapping: { '_id': 'id' }
			})

			// 更新下载次数（异步操作，不等待结果）
			patternCollection.doc(patternId).update({
				download_count: dbCmd.inc(1),
				update_time: new Date()
			}).catch(err => {
				console.error('更新下载次数失败:', err)
			})

			return {
				errCode: 0,
				data: transformedData
			}
		} catch (error) {
			if (error.errCode) {
				throw error
			}
			console.error('获取图案详情失败:', error)
			throw {
				errCode: ERROR.DICT_GET_FAILED
			}
		}
	},

	/**
	 * 通过文件名获取图案详情
	 * @param {string|string[]} fileName 图案文件名（支持单个文件名或文件名数组）
	 * @returns {object} 图案详情
	 */
	async getPatternByFileName(fileName) {
		if (!fileName) {
			throw {
				errCode: ERROR.PARAM_ERROR
			}
		}

		try {
			// 支持数组和单个文件名
			const isArray = Array.isArray(fileName)
			const fileNames = isArray ? fileName : [fileName]
			
			if (fileNames.length === 0) {
				throw {
					errCode: ERROR.PARAM_ERROR
				}
			}

			// 构建查询条件，支持批量查询
			const whereCondition = {
				file_name: fileNames.length === 1 ? fileNames[0] : dbCmd.in(fileNames),
				status: 1  // 只查询已发布的图案
			}

			// 通过 file_name 字段查询图案
			const patternResult = await patternCollection
				.where(whereCondition)
				.get()
			
			if (patternResult.data.length === 0) {
				throw {
					errCode: ERROR.DATA_NOT_FOUND
				}
			}

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 处理单个或多个结果
			if (isArray) {
				// 返回数组，保持与输入文件名数组相同的顺序
				const transformedDataList = []
				
				for (const inputFileName of fileNames) {
					const patternData = patternResult.data.find(item => item.file_name === inputFileName)
					
					if (patternData) {
						// 使用通用转换方法转换数据格式
						const transformedData = transformMultiLangData(patternData, language, {
							multiLangFields: ['pattern_name', 'description'],
							keepFields: ['category', 'difficulty', 'tags', 'pattern_file', 'file_name', 'cover_image', 'preview_image', 'thumbnail', 'duration', 'play_time', 'download_count', 'favorite_count', 'status', 'is_featured', 'designer', 'is_premium', 'compatible_devices', 'supported_languages', 'create_time', 'update_time', 'create_uid'],
							idMapping: { '_id': 'id' }
						})
						
						transformedDataList.push(transformedData)
						
						// 更新下载次数（异步操作，不等待结果）
						patternCollection.doc(patternData._id).update({
							download_count: dbCmd.inc(1),
							update_time: new Date()
						}).catch(err => {
							console.error('更新下载次数失败:', err)
						})
					}
				}
				
				return {
					errCode: 0,
					data: transformedDataList
				}
			} else {
				// 单个结果处理（保持原有逻辑兼容性）
				const patternData = patternResult.data[0]
				
				// 使用通用转换方法转换数据格式
				const transformedData = transformMultiLangData(patternData, language, {
					multiLangFields: ['pattern_name', 'description'],
					keepFields: ['category', 'difficulty', 'tags', 'pattern_file', 'file_name', 'cover_image', 'preview_image', 'thumbnail', 'duration', 'play_time', 'download_count', 'favorite_count', 'status', 'is_featured', 'designer', 'is_premium', 'compatible_devices', 'supported_languages', 'create_time', 'update_time', 'create_uid'],
					idMapping: { '_id': 'id' }
				})

				// 更新下载次数（异步操作，不等待结果）
				patternCollection.doc(patternData._id).update({
					download_count: dbCmd.inc(1),
					update_time: new Date()
				}).catch(err => {
					console.error('更新下载次数失败:', err)
				})

				return {
					errCode: 0,
					data: transformedData
				}
			}
		} catch (error) {
			if (error.errCode) {
				throw error
			}
			console.error('通过文件名获取图案详情失败:', error)
			throw {
				errCode: ERROR.DICT_GET_FAILED
			}
		}
	}
}
